<script setup>
import {User, Lock} from '@element-plus/icons-vue'
import {ref} from 'vue'
import { ElMessage } from "element-plus"
import {useAdminStore} from "@/stores/AdminStores/adminStore.js";
import {useRouter} from "vue-router";
import {loginAPI} from "@/api/AdminApi/admin.js";

const formModel = ref({
  username: 'chengqs',
  password: '123456'
})

const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 14, message: '密码长度为6-14个字符', trigger: 'blur' }
  ]
}

const adminStore = useAdminStore()
const formRef = ref(null)
const router = useRouter()
const doLogin = () => {
  const {username, password} = formModel.value
  // 调用实例方法
  formRef.value.validate(async (valid) => {
    // valid: 所有的表单都通过校验，才为true
    // console.log(valid)
    // 以valid作为判断条件，如果通过校验才执行登录逻辑
    if (valid) {
      const res = await loginAPI({username, password})
      if (res.code === 1) {
        // 1. 提示用户
        ElMessage.success('登录成功')
        adminStore.setToken(res.data.token)
        adminStore.setAdminInfo(res.data.adminInfo)
        // 2. 跳转首页
        router.replace({path: '/admin'})
      } else {
        ElMessage.error(res.msg)
      }
    }
  })
}
</script>

<template>
  <div class="form">
    <el-form class="el-form" :model="formModel" :rules="rules" ref="formRef" size="large" autocomplete="off">
      <el-form-item>
        <h1>KOKO管理员登录</h1>
      </el-form-item>
      <el-form-item class="username" prop="username">
        <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item class="password" prop="password">
        <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="button" type="primary" @click="doLogin" auto-insert-space>
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
  background-color: #dddddd;
  border: 2px solid #2c3e50;
  border-radius: 10px;
  .el-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 600px;
    height: 400px;
    .username {
      width: 500px;
    }
    .password {
      width: 500px;
    }
  }
}
</style>
